package com.zslc.foreignoption.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zslc.foreignoption.config.TweetParamProperties;
import com.zslc.foreignoption.entity.FollowAccount;
import com.zslc.foreignoption.entity.TweetAuthor;
import com.zslc.foreignoption.service.FollowAccountService;
import com.zslc.foreignoption.service.TweetAuthorService;
import com.zslc.foreignoption.service.TweetInfoService;
import com.zslc.foreignoption.util.ApifyUtil;
import com.zslc.foreignoption.util.ResultCMS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @version 1.0
 * @description:
 * @author: Gaoyc
 * @date: 2024-06-21 11:24
 **/
@Slf4j
@RequestMapping("/tweet/author")
@RestController
public class TweetAuthorController {
    @Resource
    private TweetAuthorService tweetAuthorService;
    @Resource
    private FollowAccountService followAccountService;
    @Resource
    private TweetInfoService tweetInfoService;
    @Value("${crawler.apify_token}")
    private String token;
    @Value("${crawler.push_apify_url}")
    private String pushApifyUrl;
    @Value("${crawler.tweetDataUrl}")
    private String tweetDataUrl;
    @Resource
    private TweetParamProperties tweetParamProperties;

    private final String paramFormat_global = "{\n" +
            "  \"maxItems\": %s,\n" +
            "  \"sort\": \"%s\",\n" +
            "  \"startUrls\": [\n" +
            "    \"%s\"\n" +
            "  ]\n" +
            "}\n";

    /**
     * 添加推特账户，并初始化推特帖子
     *
     * @param paramMap
     * @return com.zslc.foreignoption.util.ResultCMS
     * @author Gaoyc
     * @date 2024/06/23 13:39
     */
    @PostMapping("/info")
    public ResultCMS add(@RequestBody Map<String, String> paramMap) {
        String accountId = paramMap.get("accountId");
        String tweetName = paramMap.get("tweetName");
        if (StringUtils.isEmpty(accountId) || StringUtils.isEmpty(tweetName)) {
            return ResultCMS.fail_5101();
        }

        Integer num = 0;
        try {
            FollowAccount followAccount = followAccountService.selectOneById(accountId);
            if (!Optional.ofNullable(followAccount).isPresent()) {
                ResultCMS.fail(5101, "关注对象不存在");
            }
            TweetAuthor author = new TweetAuthor();
            tweetName = StringUtils.trim(tweetName);
            author.setUserName(tweetName);
            TweetAuthor one = tweetAuthorService.selectOneByObj(author);
            if (!Optional.ofNullable(one).isPresent()) {
                ResultCMS.fail(5001, "推特名称已存在");
            }

            JSONObject jsonObject = getAuthorDatasetId(tweetName);
            if (jsonObject != null) {
                JSONObject data = jsonObject.getJSONObject("data");
                String defaultDatasetId = data.getString("defaultDatasetId");

                Thread.sleep(10 * 1000);
                List<JSONObject> result = ApifyUtil.getTweetData(tweetDataUrl, token, defaultDatasetId);
                if (CollectionUtil.isNotEmpty(result)) {
                    log.info("【添加推特账号】从apify获取到数据，开始初始化推特信息。");
                    for (JSONObject tweetDataMap : result) {
                        String dataId = tweetDataMap.getString("id");
                        if (StringUtils.isEmpty(dataId)) {
                            continue;
                        }
                        Integer num1 = tweetInfoService.insertTweetData(tweetDataMap, accountId);
                        num++;
                    }
                }
                log.info("【添加推特账号】从apify获取到数据，初始化推特信息已结束。添加推特数据【{}】条。", num);
            } else {
                log.info("【添加推特账号】从apify获取到数据为空。");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return ResultCMS.success("初始化帖子" + num + "条");
    }

    public JSONObject getAuthorDatasetId(String tweetName) {
        try {
            String paramFormat = paramFormat_global;

            String startUrl = tweetParamProperties.getStartUrl();
            String condition = "from:%s within_time:%s";
            String q = String.format(condition, tweetName, tweetParamProperties.getWithin_time());
            String qformat = String.format(startUrl, q);
            String param = String.format(paramFormat, tweetParamProperties.getMaxItems(), tweetParamProperties.getSort(), qformat);
            log.info("推送推特作者信息数据到APIFY，组装参数：【{}】", param);

            String url = pushApifyUrl + "?token=" + token;
            JSONObject jsonObject = JSON.parseObject((HttpUtil.post(url, param)), JSONObject.class);
            log.info("推送推特作者信息数据到APIFY，返回结果：" + JSONObject.toJSONString(jsonObject));
            return jsonObject;
        } catch (Exception e) {
            log.error("推送推特作者信息数据到APIFY出错。");
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
